# -*- coding: UTF-8 -*-

import execjs
import requests
import re
import json
import cookielib

session=requests.session()
session.proxies={"127.0.0.1:8888"}
session.cookies=cookielib.LWPCookieJar()
###微博登录
def loginSina(username, password):
    phantomjs=execjs.get("PhantomJS")
    with open("./sinalogin.js", "r") as f:
        source=f.read()
    runntime=phantomjs.compile(source)
    su=runntime.call('get_name', username)
    post_url='http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)'
    prelogin_url='http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&' \
                    'su=' + su + '&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.18)'
    json_pattern=r'.*?\((.*)\)'
    repose_str=session.get(prelogin_url).text
    m=re.match(json_pattern, repose_str)
    pre_obj=json.loads(m.group(1))
    nonce = pre_obj['nonce']
    pubkey = pre_obj['pubkey']
    servertime = pre_obj['servertime']
    sp=runntime.call('get_pass', password, nonce, servertime, pubkey)
    data = {
        'entry': 'weibo',
        'gateway': '1',
        'from': '',
        'savestate': '7',
        'useticket': '1',
        'pagerefer': "http://login.sina.com.cn/sso/logout.php?entry=miniblog&r=http%3A%2F%2Fweibo.com%2Flogout.php%3Fbackurl",
        'vsnf': '1',
        'su': su,
        'service': 'miniblog',
        'servertime': pre_obj['servertime'],
        'nonce': pre_obj['nonce'],
        'pwencode': 'rsa2',
        'rsakv': pre_obj['rsakv'],
        'sp': sp,
        'sr': '1366*768',
        'encoding': 'UTF-8',
        'prelt': '115',
        'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
        'returntype': 'META',
    }
    logining_page = session.post(post_url, data=data)
    
    login_loop = logining_page.content.decode("GBK")
    pa = r'location\.replace\([\'"](.*?)[\'"]\)'
    url=re.findall(pa, login_loop)[0]
    login_info=session.get(url)
    print login_info.content
    uid = re.findall('"uniqueid":"(\d+)",', login_info.content)[0]
    result=re.findall('"result":(true|false),', login_info.content)[0]
    if bool(result) == True:    
        url = "http://weibo.com/u/" + uid
        resp = session.get(url, allow_redirects=True)
        if resp.status_code == 200:
            session.cookies.save("logincookies", ignore_discard=True, ignore_expires=True)
            return True
        else:
            return False
    else:
        return False
    
   


loginSina("1002318371@163.com", "yanghui")
#doc=BeautifulSoup(getWb(uid, resp), "html.parser")
#print(doc.prettify())


